import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import Cookies from 'js-cookie'
import request from "@/axios/axiosUtils.js";
import router from "@/router/index.js";
export const user = defineStore('user', () => {
  const token=()=>{return Cookies.get('token')};
  const userId=ref('');
  const userName=ref('');
  const avatar=ref('');
  const roles=ref([]);
  const permissions=ref([]);
  const menus=ref([]);
  function login(username, password){
    return new Promise((resolve, reject) => {
      request({
        url: '/login',
        method: 'post',
        data: {
          username,
          password
        }
      }).then(res => {
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  }
  function logout() {
    return new Promise((resolve, reject) => {
      request({
        url: '/logout',
        method: 'post'
      }).then((res) => {
        Cookies.remove('token');
        resolve(res);
        userId.value = '';
        userName.value = '';
        avatar.value = '';
        roles.value = [];
        permissions.value = [];
        resolve(res);
      }).catch(error => {
        reject(error);
      })
    })
  }
    function getInfo(){
      return new Promise((resolve, reject) => {
        request({
          url: '/userInfo',
          method: 'get'
        }).then(res => {
          const userDTO = res.data;
          userId.value = userDTO.id;
          userName.value = userDTO.username;
          avatar.value = userDTO.avatar;
          roles.value = userDTO.roles;
          permissions.value = userDTO.authorities;
          menus.value = userDTO.menus;
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    }
    function register(user){
      return new Promise((resolve, reject) => {
        request({
          url: '/register',
          method: 'post',
          data: user
        }).then(res => {
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    }
  return {
    token,
    userId,
    userName,
    avatar,
    roles,
    permissions,
    menus,
    login,
    logout,
    getInfo,
    register
  }
})
export const dynamicRoutes = defineStore('dynamicRoutes', () => {
  const routes = ref([])
  const addRoutes = (routes) => {
    routes.forEach(route => {
      router.addRoute(route)
    })
  }
  return {
    routes,
    addRoutes
  }
}
)
